const selectMoreConfig = {
	"url":"./demo.json", // ajax请求地址
	"option_value_key":"areaId",  //  option配置中 value取值的key 例如：<option value="areaId"></option>
	"option_text_key":"name",     // option配置中 text取值的key  例如：<option value="areaId"></option>
	"params_pid_key":"parentId",  // ajax查询目标ID下子集的参数名 例如：params:{"parentId":1}
	"params_pid_def":0, // 初始化第一级数据时 默认参数值
}
layui.define(['form'],function(exports){
	var form = layui.form;
	var $ = layui.$;

	// 构建地区option
	function buildRegionSelect(target,data){
		var html = "";
		for(var k in data){
			html += '<option value="'+data[k][selectMoreConfig.option_value_key]+'">'+data[k][selectMoreConfig.option_text_key]+'</option>';
		}
		var target_dom = typeof(target)=='string'?$(target):target;
		$(target_dom).html(html);

		var def = target_dom.attr("data-def");
		if(def){
			$(target_dom).val(def);
			changeArea(target_dom);
		}
		var target_son = target_dom.attr("data-target");

		if(target_son&&data.length>0){
			var pid = data[0][selectMoreConfig.option_value_key];
			var p = {};
			p[selectMoreConfig.params_pid_key] = pid;
			selectRegionData(target_son,p);
		}
		form.render("select");
	}

	// 查询地区数据
	function selectRegionData(target,params={}){
		$.ajax({
			url:selectMoreConfig.url,
			type:'get',
			data:params,
			success:function(res){
				// 这里可以根据系统业务逻辑 增加逻辑判断
				if(res.code==200){
					buildRegionSelect(target,res.data);
				}else{
					alert("数据请求失败");
				}
			}
		});
	}

	function changeArea(dom){
		var target = dom.attr("data-target");
		if(target){
			var pid = dom.val();
			var p = {};
			p[selectMoreConfig.params_pid_key] = pid;
			selectRegionData(target,p);
		}
	}
	// 表单监听
	form.on('select(selectMore)', function(data){
  		var dom = $(data.elem);
  		changeArea(dom);
	});

	var selectMore = {
		init:function(target){
			var p = {};
			p[selectMoreConfig.params_pid_key] = selectMoreConfig.params_pid_def;
			selectRegionData(target,p);
		},
		set:function(target,value){
			layui.$(target).attr("data-def",value);
			layui.$(target).val(value);
			changeArea(layui.$(target));
		},
		setAll:function(data=[]){
			for (var i = 0,l=data.length; i < l ; i++) {
				layui.$("select[lay-filter='selectMore']").eq(i).attr("data-def",data[i]);
				layui.$("select[lay-filter='selectMore']").eq(i).val(data[i]);
				changeArea(layui.$("select[lay-filter='selectMore']").eq(0));
			}
		}
	};
	exports('selectMore', selectMore);
});